package com.myplaylist.android.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class Discoverer {

	private WifiManager wifiManager;
	private InetAddress broadcastAddress;
	//private Socket socket;
	


	public Discoverer(WifiManager wifiManager) {
		this.wifiManager = wifiManager;
	}

	public NetworkInfoCredentials discover() {
		try {
			broadcastAddress = getBroadcastAddress();
			Log.i("BROADCAST ADDRESS: ", broadcastAddress.toString());
			
			DatagramSocket dSocket = new DatagramSocket(4321);
			dSocket.setBroadcast(true);
			
			String data = "PING";
			
			DatagramPacket packet = new DatagramPacket(data.getBytes(), data.getBytes().length, broadcastAddress, 4321);
			dSocket.send(packet);
			
			String response1;
			String response2;
				
			byte[] byteData = new byte[5000];
			DatagramPacket anotherPacket = new DatagramPacket(byteData, byteData.length);
			dSocket.receive(anotherPacket);
			ByteArrayInputStream bais = new ByteArrayInputStream(
					anotherPacket.getData());
			BufferedReader ois = new BufferedReader(new InputStreamReader(
					bais));
			response1 = ois.readLine().trim();

			Log.i("first read: SERVER IP/PING is:", response1);
			
			byteData = new byte[5000];
			anotherPacket = new DatagramPacket(byteData, byteData.length);
			dSocket.receive(anotherPacket);
			bais = new ByteArrayInputStream(
					anotherPacket.getData());
			ois = new BufferedReader(new InputStreamReader(
					bais));
			response2 = ois.readLine().trim();
			
			dSocket.close();
			
			Log.i("second read: SERVER IP/PING is:", response2);
			
			NetworkInfoCredentials networkInfoCredentials = null;
			
			if (response1.trim().equals("PING")) {
				//sendXmlDataToServer(response2);
				String[] strings = response2.split("/");
				String[] networkCredentials = strings[1].split(":");
				String serverIp = networkCredentials[0];
				String serverPort = networkCredentials[1];
				networkInfoCredentials = new NetworkInfoCredentials(serverIp, serverPort);
			} else {
				//sendXmlDataToServer(response1);
				String[] strings = response1.split("/");
				String[] networkCredentials = strings[1].split(":");
				String serverIp = networkCredentials[0];
				String serverPort = networkCredentials[1];
				networkInfoCredentials = new NetworkInfoCredentials(serverIp, serverPort);
			}
			
			return networkInfoCredentials;
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/*private void sendXmlDataToServer(String response) throws NumberFormatException, UnknownHostException, IOException {
		Log.i("Data: ", response);
		String[] strings = response.split("/");
		String[] networkCredentials = strings[1].split(":");
		String serverIp = networkCredentials[0];
		String serverPort = networkCredentials[1];
		
		
		
		XmlSerializer xmlSerializer = Xml.newSerializer();
		StringWriter stringWriter = new StringWriter();
		
		try {
			xmlSerializer.setOutput(stringWriter);
			xmlSerializer.startDocument("UTF-8", true);
			xmlSerializer.startTag("", "tracklist");
			
			xmlSerializer.startTag("", "track");
			xmlSerializer.attribute("", "title", "Igyunk palinkat");
			xmlSerializer.attribute("", "author", "Firkin");
			xmlSerializer.attribute("", "score", "10");
			xmlSerializer.endTag("", "track");
			
			xmlSerializer.startTag("", "track");
			xmlSerializer.attribute("", "title", "Imagine");
			xmlSerializer.attribute("", "author", "John Lennon");
			xmlSerializer.attribute("", "score", "9");
			xmlSerializer.endTag("", "track");
			
			xmlSerializer.startTag("", "track");
			xmlSerializer.attribute("", "title", "One");
			xmlSerializer.attribute("", "author", "U2");
			xmlSerializer.attribute("", "score", "8");
			xmlSerializer.endTag("", "track");
			
			xmlSerializer.startTag("", "track");
			xmlSerializer.attribute("", "title", "Sacrifice");
			xmlSerializer.attribute("", "author", "Elton John");
			xmlSerializer.attribute("", "score", "7");
			xmlSerializer.endTag("", "track");
			
			xmlSerializer.startTag("", "track");
			xmlSerializer.attribute("", "title", "The sweet");
			xmlSerializer.attribute("", "author", "AC DC");
			xmlSerializer.attribute("", "score", "6");
			xmlSerializer.endTag("", "track");
			
			xmlSerializer.startTag("", "track");
			xmlSerializer.attribute("", "title", "We are the champions");
			xmlSerializer.attribute("", "author", "Queen");
			xmlSerializer.attribute("", "score", "5");
			xmlSerializer.endTag("", "track");
			
			xmlSerializer.startTag("", "track");
			xmlSerializer.attribute("", "title", "Desert rose");
			xmlSerializer.attribute("", "author", "Sting");
			xmlSerializer.attribute("", "score", "4");
			xmlSerializer.endTag("", "track");
			
			xmlSerializer.startTag("", "track");
			xmlSerializer.attribute("", "title", "My heart will go on");
			xmlSerializer.attribute("", "author", "Celine Dion");
			xmlSerializer.attribute("", "score", "3");
			xmlSerializer.endTag("", "track");
			
			xmlSerializer.startTag("", "track");
			xmlSerializer.attribute("", "title", "Always");
			xmlSerializer.attribute("", "author", "Bon Jovi");
			xmlSerializer.attribute("", "score", "2");
			xmlSerializer.endTag("", "track");
			
			xmlSerializer.startTag("", "track");
			xmlSerializer.attribute("", "title", "Don't stop me know");
			xmlSerializer.attribute("", "author", "Queen");
			xmlSerializer.attribute("", "score", "1");
			xmlSerializer.endTag("", "track");
			
			xmlSerializer.endTag("", "tracklist");
			xmlSerializer.endDocument();
			
			socket = new Socket(InetAddress.getByName(serverIp), Integer.parseInt(serverPort));
			
			PrintWriter pw = new PrintWriter(socket.getOutputStream());
			
			Log.i("XML String", stringWriter.toString());
			
			pw.write(stringWriter.toString());
			pw.flush();
			
			pw.close();
			
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (socket != null) {
				socket.close();
			}
		}
		
	}*/

	private InetAddress getBroadcastAddress() throws UnknownHostException {
		InetAddress result = null;
		
		DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
		if ( dhcpInfo != null) {
			int broadcast = (dhcpInfo.ipAddress & dhcpInfo.netmask) | ~dhcpInfo.netmask;
			byte[] quads = new byte[4];
			for (int i = 0; i < 4; i++) {
				quads[i] = (byte) ((broadcast >> i * 8) & 0xFF);
				System.out.println("" + quads[i]);
			}
			result = InetAddress.getByAddress(quads);
		}
		
		return result;
	}

	
	
	
}
